package com.hnkywl.sts.util;

import com.hnkywl.sts.action.portal.LoginAction;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * User: 灵韵
 * Date: 13-9-12
 * Time: 下午2:39
 * To change this template use File | Settings | File Templates.
 */
public class CookieUtils {
    public static final String USER_COOKIE = "user.cookie";

    // 添加一个cookie
    public Cookie addCookie(String userName) {
        userName=java.net.URLEncoder.encode(userName);
        Cookie cookie = new Cookie(USER_COOKIE, userName);
        cookie.setMaxAge(60 * 60 * 24 * 30);// cookie保存两周
        return cookie;
    }

    // 得到cookie
    public String getCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (CookieUtils.USER_COOKIE.equals(cookie.getName())) {
                    String value = cookie.getValue();
                    value=java.net.URLDecoder.decode(value);
                    return value;
                }
            }
        }
        return null;
    }

    // 删除cookie
    public Cookie delCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (USER_COOKIE.equals(cookie.getName())) {
                    cookie.setValue("");
                    cookie.setMaxAge(0);
                    return cookie;
                }
            }
        }
        return null;
    }
}
